package com.example.appbarapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import android.os.Bundle;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.ArrayList;
import java.util.List;

/*
实践要点：
1.准备图片素材，并创建Fragment类（xml和java class类）
2.在Activity布局文件中引入                                                                                                                              控件
3.创建Fragment适配器，继承FragmentStateAdapter类，并复写override方法：定义Fragment列表成员变量，并生成包含成员变量的构造方法
4.在Activity中完成列表数据初始化操作，实例化适配器将Fragment加载入ViewPager2，并借助TabLayoutMediator类完成选项卡标题的载入和两者联动
 */


public class MainActivity extends AppCompatActivity {

    private ViewPager2 viewPager2;
    private TabLayout tabLayout;
    private List<String> titles;
    private  List<Fragment> fragmentList;
    private MyFragmentAdapter fragmentAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tabLayout = findViewById(R.id.top_tab);
        viewPager2 = findViewById(R.id.view_pager2);

        initTab();
    }

    /*初始化导航栏Tab及Fragment界面*/
    private void initTab() {
        titles = new ArrayList<String>();
        titles.add("关注");
        titles.add("发现");
        titles.add("消息");
        titles.add("我");

        Fragment1 fragment1 = new Fragment1();
        Fragment2 fragment2 = new Fragment2();
        Fragment3 fragment3 = new Fragment3();
        Fragment4 fragment4 = new Fragment4();

        fragmentList = new ArrayList<Fragment>();
        fragmentList.add(fragment1);
        fragmentList.add(fragment2);
        fragmentList.add(fragment3);
        fragmentList.add(fragment4);

        /*借用FragmentStateAdapter将Fragment配置到ViewPager2中*/
        fragmentAdapter = new MyFragmentAdapter(MainActivity.this,fragmentList);
        viewPager2.setAdapter(fragmentAdapter);

        /*借助TabLayoutMediator实现TabLayout和ViewPager2的联动*/
        new TabLayoutMediator(tabLayout, viewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                tab.setText(titles.get(position));
            }
        }).attach();
    }
}